import * as Cesium from "cesium";
import BaseDraw from "./BaseDraw";

/**
 * 派生类-绘制圆形
 *
 */
export default class DrawCircle extends BaseDraw {
  constructor(options) {
    super(options);
    this.currentDrawId = this.generateUUID(); // 当次绘制的-id
    this.labelEntity = null; // 当次绘制的-标签实例
    this.circleEntry = null; // 当次绘制的-圆实例
    this.positionList = []; // 当次绘制的笛卡尔数组
  }
  // 重置绘制中间量
  resetDraw() {
    this.currentDrawId = this.generateUUID(); // 当次绘制的-id
    this.labelEntity = null; // 当次绘制的-标签实例
    this.circleEntry = null; // 当次绘制的-圆实例
    this.positionList = []; // 当次绘制的笛卡尔数组
  }
  // 实体加入到集合管理类中进行管理
  addEntityCollection(entity) {
    this.entityCollection.add(entity, this.currentDrawId);
  }
  getAllEntity() {
    return this.entityCollection.getAll();
  }
  // 关闭 CallbackProperty的计算，取最后一次的结果
  removeCallbackProperty() {
    const circleEntry = this.circleEntry;
    const labelEntity = this.labelEntity;
    if (circleEntry) {
      circleEntry.ellipse.semiMinorAxis =
        circleEntry.ellipse.semiMinorAxis.getValue();
      circleEntry.ellipse.semiMajorAxis =
        circleEntry.ellipse.semiMajorAxis.getValue();

      // 验证
      // console.log("removeCallbackProperty", {
      //   semiMinorAxis: circleEntry.ellipse.semiMinorAxis,
      //   semiMajorAxis: circleEntry.ellipse.semiMajorAxis,
      // });
    }
    if (labelEntity) {
      labelEntity.label.text = labelEntity.label.text.getValue();
    }
  }
  // 计算半径的 property 属性
  createRadiusProperty() {
    const _this = this;
    const positionList = this.positionList;
    const radiusProperty = new Cesium.CallbackProperty(function () {
      //计算半径 =  两点间距离
      // 1. 笛卡尔坐标转经纬度坐标
      const g1 = _this._coorder.cartesian3ToLonLatHeight(positionList[0]);
      const g2 = _this._coorder.cartesian3ToLonLatHeight(
        positionList[positionList.length - 1]
      );
      // 2.经纬度坐标转弧度制坐标
      const satrt = Cesium.Cartographic.fromDegrees(g1[0], g1[1]);
      const end = Cesium.Cartographic.fromDegrees(g2[0], g2[1]);
      // 3.计算测地线距离
      const geodesic = new Cesium.EllipsoidGeodesic(satrt, end); // 弧度制坐标
      return geodesic.surfaceDistance; // 获取两点间测地线距离
    }, false);
    return radiusProperty;
  }
  // 生成圆实体
  creatCircleEntity() {
    const _this = this;
    const positionList = this.positionList;
    const cartesian = positionList[positionList.length - 1]; // 最后一个点的笛卡尔坐标
    const radiusProperty = this.createRadiusProperty(); // 半径计算
    const entity = new Cesium.Entity({
      position: _this.positionList[0],
      ellipse: {
        semiMinorAxis: radiusProperty, // 圆形的短轴半径
        semiMajorAxis: radiusProperty, // 圆形的长轴半径
        material: Cesium.Color.YELLOW.withAlpha(0.1),
        outline: true,
        outlineColor: Cesium.Color.RED,
        outlineWidth: 1,
        height: _this.ellipsoid.cartesianToCartographic(cartesian).height,
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
      },
    });
    console.log("圆形实体", entity);
    return entity;
  }
  // 生成标注实体
  creatLabelEntity() {
    const _this = this;
    const positionList = this.positionList;
    const radiusProperty = _this.createRadiusProperty(); // 半径计算
    const entity = new Cesium.Entity({
      position: positionList[0], // 世界坐标
      label: {
        text: new Cesium.CallbackProperty(() => {
          if (_this.positionList.length > 0) {
            const r = radiusProperty?.getValue();
            const area = this._caculater.CircleArea(_this.positionList[0], r); // 计算面积，得到平方米
            if (area > 1000000) {
              return "面积:" + (area / 1000000).toFixed(2) + "平方公里";
            } else {
              return "面积:" + area.toFixed(2) + "平方米";
            }
          } else {
            return "0";
          }
        }, false),
        font: "20px",
        color: Cesium.Color.RED,
        pixelOffset: new Cesium.Cartesian2(0, 0),
        fillColor: Cesium.Color.WHITE,
        showBackground: true,
        backgroundColor: Cesium.Color.BLUE,
      },
    });
    return entity;
  }
}

/**
 * 开始绘制点
 * @param {* 是否显示测量Label} showMeasureLabel
 * @param {* 是否连续绘制} continuousDraw
 *
 */
DrawCircle.prototype.startDraw = function (
  showMeasureLabel = true,
  continuousDraw = true
) {
  const _this = this;
  this.resetDraw(); // 重置绘制中间量
  const customType = this.customType; // 事件类型
  this._tip.show("单击开始绘制");
  // 左键点击事件
  this._handler.addHandelEvent(
    (event) => {
      const cartesian = this._coorder.ScreenToCartesian3(event.position); // 屏幕坐标转世界坐标
      if (!Cesium.defined(cartesian)) return;
      _this.positionList.push(cartesian.clone());
      // 生成标注
      if (showMeasureLabel && !_this.labelEntity) {
        _this.labelEntity = _this.creatLabelEntity();
        this.addEntityCollection(_this.labelEntity);
      }
      // 如果圆实体不存在，开始绘制圆
      if (!_this.circleEntry) {
        _this.circleEntry = _this.creatCircleEntity();
        this.addEntityCollection(_this.circleEntry);
        _this._tip.changeText("再次点击结束绘制");
      } else {
        // 点击第二次结束绘制
        this.endDraw();
        if (continuousDraw) {
          // 绘制完后再次绘制
          this.startDraw(showMeasureLabel);
        }
      }
    },
    customType,
    Cesium.ScreenSpaceEventType.LEFT_CLICK
  );
  // 鼠标移动事件
  this._handler.addHandelEvent(
    (event) => {
      if (_this.circleEntry) {
        const cartesian = this._coorder.ScreenToCartesian3(event.endPosition); // 屏幕坐标转世界坐标
        if (Cesium.defined(cartesian)) {
          const positionList = _this.positionList;
          if (positionList.length === 1) {
            positionList.push(cartesian.clone());
          } else if (positionList.length >= 2) {
            positionList.pop();
            positionList.push(cartesian.clone());
          }
        }
      }
      const { x, y } = event.endPosition;
      _this._tip.moveTipDOMPosition(x, y); // 改变 TipDOM 位置
    },
    customType,
    Cesium.ScreenSpaceEventType.MOUSE_MOVE
  );
  // 右键点击事件
  this._handler.addHandelEvent(
    (event) => {
      this.endDraw();
    },
    customType,
    Cesium.ScreenSpaceEventType.RIGHT_CLICK
  );
};

/**
 * 结束绘制点
 */
DrawCircle.prototype.endDraw = function () {
  this._tip.close();
  this.removeCallbackProperty(); // 清除 callbackProperty 的执行
  const customType = this.customType;
  this._handler.removeHandelEvnet(
    customType,
    Cesium.ScreenSpaceEventType.LEFT_CLICK
  );
  this._handler.removeHandelEvnet(
    customType,
    Cesium.ScreenSpaceEventType.MOUSE_MOVE
  );
  this._handler.removeHandelEvnet(
    customType,
    Cesium.ScreenSpaceEventType.RIGHT_CLICK
  );
};
/**
 * 清除绘制的点
 */
DrawCircle.prototype.removeDraw = function () {
  this.entityCollection.removeAll();
};
